/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.filterX;

import acceso.util.LogueoHelper;
import java.io.IOException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author john
 */
public class Logueo implements Filter {

    private FilterConfig filterConfig = null;
//    private static boolean logueo = true;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        System.out.println("[Filtro logueo]");

        if (req.getSession().getAttribute("US") == null) {
            //validar si tiene los parametros para iniciar sesion automaticamente
            Map params = request.getParameterMap();

            if (params.get("usu") != null && params.get("pwd") != null) {
                boolean r = LogueoHelper.loguear(req);
                if (r) {
                    chain.doFilter(request, response);
                } else {
                    req.setAttribute("url", req.getRequestURL() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                    RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                    dispatcher.forward(req, res);
                }
            } else {
                if ((new String(req.getRequestURL())).indexOf("wg") > -1 | (new String(req.getRequestURL())).indexOf("wfm") > -1 | (new String(req.getRequestURL())).indexOf("link") > -1) {
                    req.setAttribute("url", req.getRequestURL() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                }
                System.out.println("[Filtro logueo]Se requiere logueo");
                RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                dispatcher.forward(req, res);
            }
        } else {
            chain.doFilter(request, response);
        }

    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
//        logueo = ((Bulldozer) filterConfig.getServletContext().getAttribute("acceso")).getWorkflow().isLogueo();
    }

    public synchronized static void update_filter(boolean l) {
//        System.out.println("update logueo[" + logueo + ":" + l + "]");
//        logueo = l;

    }
}
